# -*- coding: utf-8 -*-
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError
from odoo import api, http, models,fields,_,SUPERUSER_ID
import psycopg2

HOST="ecmec.com.cn"
PORT=443
DB_NAME="odoo16-test"
LOGIN="admin"
PASSWD='DIbohao1'
# 数据库连接参数设置
pg_admin = 'postgres' # 指定用户名
pg_passwd = '560227' # 指定用户密码 ,保密，不对外公布了，以*代替了
pg_port = "5432" # 指定数据库端口号

class MeasCtlInit(models.Model):
    _name="meas.ctl.init"
    _description="下载服务器端地res.company及res.users" 

    def dbh_update_company(self):
        if self.env['meas.ctl.work.sub'].search([]):
            raise ValidationError('初始化元数据前,必须将工单数据上传！')
        self.env['meas.ctl.tool.info'].search([]).unlink()    

        domain=[('parent_id','!=',False)]
        fields=['name','active','parent_id']
        result=self.env['meas.ctl.rpc'].fetch_data(domain,'res.company',fields)
        # 将当前的self.env.company改成用户默认的company_id。不成功！还是界面上切换
        # selfEnv=self
        # self=self.env.user
        # self=self.with_company(self.env.user.company_id)
        # self=selfEnv

        self_companies=self.env['res.company'].search([('id','!=',self.env.user.company_id.id)])
        self_partner=self_companies.mapped('partner_id')
        self_companies.user_ids=[(5,0)]
        self_companies.unlink()
        self_partner.unlink()
        for r in result:
            self.env['res.company'].create({
            'name':r['name'],
            'active':r['active'],
            'co_id':r['id'],
            })
        # company的服务器端与本地id对应字典
        co_id_dict=self.dbh_get_company_id_rel()
        #服务器端的parent_id转换成本地相应的id,并更新本地
        for rec in self.env['res.company'].search([('id','!=',self.env.user.company_id.id)]):
            p_id=self.env['meas.ctl.rpc'].find_dict_by_value(result, 'id', rec.co_id) and self.env['meas.ctl.rpc'].find_dict_by_value(result, 'id', rec.co_id)['parent_id'][0]
            if p_id:
                parent_id=co_id_dict.get(p_id,False) or self.env.user.company_id.id
            else:    
                parent_id=self.env.user.company_id.id 
            rec.update({
                'parent_id':parent_id
                })
        return    
    def dbh_update_users(self):
        domain=[('active','=',True),('share','=',False),('login','!=','admin')]
        fields=['login','name','share','active','company_id','email','company_ids']
        result=self.env['meas.ctl.rpc'].fetch_data(domain,'res.users',fields)
        #通过sql获取服务端的password,以便后面通个sql加到本地用户中。odoo orm会将新填入的password在加密，以及看不到password
        conn = psycopg2.connect(database='odoo16-test',user='postgres',password='560227',host='ecmec.com.cn',port='5432')
        cr = conn.cursor()
        cr.execute("select login,password from res_users where active=True and share = False and login != 'admin';")
        odoo_passwd_users = cr.fetchall() 
        cr.close() 
        passwd_dict=dict(odoo_passwd_users)
        pass
        # company的服务器端与客户端id对应字典
        co_id_dict=self.dbh_get_company_id_rel()
        self.env['res.users'].sudo().search([('active','=',True),('share','=',False),('login','!=','admin')]).unlink()
        for r in result:
            nu=self.env['res.users'].sudo().create({
                'login':r['login'],
                'name':r['name'],
                'share':r['share'],
                'active':r['active'],
                'user_id':r['id'],
                'email':r['email']
            })
            company_ids=[]
            # 将服务器的res.users.company_ids列表，转换成本地的company_ids
            for i in r['company_ids']:
                if i in co_id_dict:
                    company_ids.append(co_id_dict[i])
            # 设置本地company_ids: 如果用（6，0 ，company_is）会清楚前面的（当前默认的company_id）报错        
            nu.company_ids=[(4,lst) for lst in company_ids]
            if r['company_id'][0] in co_id_dict:
                nu.company_id=co_id_dict[r['company_id'][0]]
                nu.company_ids=[(3,self.env.user.company_id.id)] #清除允许公司列表中的默认
            # 用sql语句直接更新password,这样不会再加密    
            passwd=passwd_dict[r['login']]
            self.env.cr.execute('update res_users set password=%s where id=%s',(passwd,nu.id))    
        return
    def dbh_get_company_id_rel(self):
        # 创建company的服务器端与客户端id对应字典.co_id->company_id
        com=self.env['res.company'].sudo().search([('id','!=',self.env.user.company_id.id)])
        co_id_dict=dict(zip(com.mapped('co_id'),com.ids))
        return co_id_dict

    def dbh_init(self):
        self.dbh_update_company()
        self.dbh_update_users()

class Users(models.Model):
    _inherit="res.users"
    user_id=fields.Integer('用户ID')
    company_id = fields.Many2one('res.company', string='Company',ondelete='cascade')
class Company(models.Model):
    _inherit = "res.company"
    co_id=fields.Integer('公司ID')    